<?php
namespace app\api\controller;

use app\common\model\Member;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;


class Index extends Common
{
    public function regionList()
    {
        $model = model('Region');
        $lists = $model->field('')->where(['areaGrade' => 0])->select();
        $this->result['list'] = $lists;
        $this->result['totalSize'] = count($lists);
        return $this->ajax_return();
    }
    public function sonAreaInfoList()
    {
        $parentAreaCode = input('parentAreaCode', '');
        $model = model('Region');
        $lists = $model->field(true)->where(['parentId' => $parentAreaCode])->select();
        $this->result['list'] = $lists;
        $this->result['totalSize'] = count($lists);
        return $this->ajax_return();
    }
    public function index()
    {
        $db_info = model('BranchList')->where('id', 7)->value('db_info');
        $db_info = json_decode(htmlspecialchars_decode($db_info), true);

        try {
            $this->oracleDb = Db::connect($db_info);
            return $this->oracleDb->table('SERVICE')->where(['CODE' => 'A'])->value('ID');
        } catch (\PDOException $pdoExp) {
            $this->result['error'] = 1;
            $this->result['msg'] = 'oracle 初始化失败';
            return ajax_return_error($pdoExp->getMessage());
        }
    }

    /**
     * 业务列表
     */
    public function businessList()
    {
        $model = model('BusinessList');
        $lists = $model->field(true)->where(['isdelete' => 0])->select();
//        foreach ($lists as &$list) {
//        }
        return ajax_return($lists);
    }


    /**
     * 新网点列表
     */
    public function newBranchList()
    {
        $myLng = input('mylng', '');  //用户地理位置经度
        $myLat = input('mylat', '');  //用户地理位置纬度
        $orderType = input('ordertype', 0);  //0 按距离排序  1：按排队人数
        if ($orderType == 0 && (empty($myLng) || empty($myLng))) {
            return ajax_return_error('参数有误');
        }
        $model = model('BranchList');
        $lists = $model->field('id,name,address,latitude, longitude,status')->where(['isdelete' => 0,'status'=>1])->select();
        if ($lists) {
            foreach ($lists as &$list) {
                //一。.查询此类业务正在排队的有多少人
                $list->queueNum = model('Queue')->where(['branchid' => $list->id])->count('1') ?: 0;

                //二。计算 两个点之间的距离
                $list->distance = get_distance($myLat, $myLng, $list->latitude, $list->longitude);
            }
        }
        if ($orderType == 0) {
            $lists = obj_list_sort_by($lists, 'distance', 'asc');
        } else {
            $lists = obj_list_sort_by($lists, 'queueNum', 'asc');
        }
        return ajax_return($lists);

    }

    /**
     * 新业务列表
     */
    public function newBusinessList()
    {
        $branchId = input('branchid', 0);  //网点id
        if (empty($branchId)) {
            return ajax_return_error('参数为空');
        }
        //获取此网点开通的业务
        $bisIds = model('BranchBusiness')->where('branchid', $branchId)->column('bisid');
        if ($bisIds) {
            $businessListModel = model('BusinessList');
            $lists = array();
            foreach ($bisIds as $key => $bisId) {
                // 查看是否开放
                $lists[$key] = $businessListModel->field(true)
                    ->where(['id' => $bisId, 'isdelete' => 0])->find();
                if (!$lists[$key]) {
                    continue;
                }
            }
            $lists = array_filter($lists);

            $lists = obj_list_sort_by($lists, 'id', 'asc');

            return ajax_return($lists);
        }

        return ajax_return_error('网点暂未开通业务');
    }

    /**
     * 预约列表
     */
    public function queueOrderList()
    {
        $status = input('status', 1);  // 1:正常  -1 ：取消  2：已排队

        $model = model('QueueOrder');
        $lists = $model->field(true)->where(['uid' => $this->uid, 'status' => $status])->select();
        if ($lists) {
            foreach ($lists as &$list) {
                $list->queue_time = date('Y年m月d日 H:i', $list->queue_time);
//                $list->create_time = date('Y年m月d日', $list->create_time);

            }
        }

        return ajax_return($lists);
    }

    /**
     * 取消预约
     */
    public function cancelQueueOrder()
    {
        $id = input('post.id', 0);  // 1:正常  -1 ：取消  2：已排队
        if (empty($id)) {
            return ajax_return_error('参数为空');
        }

        $model = model('QueueOrder');
        $info = $model->field(true)->where(['id' => $id, 'uid' => $this->uid, 'status' => 1])->find();
        if (empty($info)) {
            return ajax_return_error('参数有误');
        }
        $boolean = $info->where(['id' => $id])->update(['status' => -1]);
        if ($boolean) {
            return ajax_return('success');
        }

        return ajax_return_error('cancel failure');
    }

    /**
     * 网店列表
     */
    public function branchList()
    {

        $bisId = input('bisid', 0);  //业务id
        $mylng = input('mylng', '');  //用户地理位置
        $mylat = input('mylat', '');  //用户地理位置
        $orderType = input('ordertype', 0);  //0 按距离排序  1：按排队人数
        if (empty($bisId) || empty($mylng) || empty($mylat)) {
            return ajax_return_error('参数为空');
        }
        //获取开通此业务的网点
        $branchIds = model('BranchBusiness')->where('bisid', $bisId)->column('branchid');
        //获取此业务的编码
        $bisCode = model('BusinessList')->where('id', $bisId)->value('code') ?: '';

        if ($branchIds) {
            $branchListModel = model('BranchList');
            $lists = array();
            foreach ($branchIds as $key => $branchId) {
                //过滤时间  查看是否营业
                $lists[$key] = $branchListModel->field('id,code,name,address,times,longitude,latitude')
                    ->where(['id' => $branchId, 'isdelete' => 0, 'status' => 1])->find();
                if (!$lists[$key]) {
                    continue;
                }
                //过滤时间
                $lists[$key]->times = json_decode(htmlspecialchars_decode($lists[$key]->times), true);


                //一。获取前面排队的人数
                //1.获取排队机上的业务id
                $serviceId = $this->getRemoteServiceId($branchId, $bisCode);
                if($this->result['error']){
                    $this->ajaxReturn($this->result);
                }
                //2.查询此类业务正在排队的有多少人
//                $lists[$key]->queueNum = $this->oracleDb->table('QUEUE')->where('service', $serviceId)->count('id') ?: 0;
                $lists[$key]->queueNum = model('Queue')->where(['branchid' => $branchId, 'serviceid' => $serviceId])->count('1') ?: 0;

                //二。计算 两个点之间的距离
                $lists[$key]->distance = get_distance($mylat, $mylng, $lists[$key]['latitude'], $lists[$key]['longitude']);
            }
            $lists = array_filter($lists);
            if ($orderType == 0) {
                $lists = obj_list_sort_by($lists, 'distance', 'asc');
            } else {
                $lists = obj_list_sort_by($lists, 'queueNum', 'asc');
            }

            return ajax_return($lists);

        }

        return ajax_return_error('暂无网点开通此项业务');
    }

    /**
     * 排号主界面
     */
    public function branchInfo()
    {
        $bisId = input('bisid', 0);  //业务id
        $branchId = input('branchid', 0);  //网点id

        if (empty($bisId) || empty($branchId)) {
            return ajax_return_error('参数为空');
        }

        //1.获取此业务的编码,名称
        $bisInfo = model('BusinessList')->field('code,name,data,buss_flow')->find($bisId);
        $data['bisname'] = $bisInfo->name ?: '';
        $data['data'] = $bisInfo->data ?: '';


        $model = model('ArticleList');
        $articleInfo = $model->where('isdelete', 0)->find($bisInfo->buss_flow);
        if ($articleInfo) {
            $articleInfo->content = htmlspecialchars_decode($articleInfo->content);
        }
        $data['buss_flow'] = $articleInfo->content ?: '';

        //2.获取排队机上的业务id
        $serviceId = $this->getRemoteServiceId($branchId, trim($bisInfo->code));
        if($this->result['error']){
            $this->ajaxReturn($this->result);
        }
        //3.获取正在受理的编号

        $dayStart = strtotime(date('Y-m-d'));
        $dayEnd = $dayStart + 3600 * 24;
        $data['nextQueueCode'] = model('QueueHistory')->where(['branchid' => $branchId, 'serviceid' => $serviceId, 'handle_start_time' => [['>', $dayStart], ['<', $dayEnd]]])
            ->order('queue_time', 'DESC')->value('queue_code') ?: '暂未受理';
//        $data['sql'] = model('QueueHistory')->getLastSql();
        //4.查询此类业务正在排队的有多少人
//        $data['waitNum'] = $this->oracleDb->table('QUEUE')->where('service', $serviceId)->count('id') ?: 0;
        $data['waitNum'] = model('Queue')->where(['branchid' => $branchId, 'serviceid' => $serviceId])->count('1') ?: 0;

        return ajax_return($data);

    }

    /**
     * 我的排号主界面
     */
    public function myBranchInfo()
    {
        $queueInfo = model('Queue')->field('branchid, bisid,queue_code, queue_sn,queue_time')->where(['uid' => $this->uid])
            ->order('queue_time', 'DESC')->find();

        if (!$queueInfo) {
            $queueInfo = model('QueueHistory')->field('branchid, bisid,queue_code, queue_sn,queue_time')->where(['uid' => $this->uid])
                ->order('queue_time', 'DESC')->find();
        }
        if (!$queueInfo) {
            return ajax_return_error('未查询到您的排队记录');
        }
        $bisId = $queueInfo->bisid ?: 0;
        $branchId = $queueInfo->branchid ?: 0;
        $data['code'] = $queueInfo->queue_code ?: 0;
        $data['bisid'] = $bisId;

        //1.获取此业务的编码,名称
        $bisInfo = model('BusinessList')->field('code,name,data')->find($bisId);
        $data['bisname'] = $bisInfo->name ?: '';

        //2.获取排队机上的业务id
        $serviceId = $this->getRemoteServiceId($branchId, trim($bisInfo->code));
        if($this->result['error']){
            $this->ajaxReturn($this->result);
        }
        $this->getOracleDb($branchId);
        if ($this->result['error']) {
            return ajax_return_error($this->result['msg']);
        }


        //4.查询此类业务正在排队的有多少人
        $sql = "select count(1) as num from QUEUE where service = $serviceId ";
        if ($queueInfo) {
            $sql .= "AND FCD<to_date('" . date('Y-m-d H:i:s', $queueInfo->queue_time) . "','yyyy-mm-dd hh24:mi:ss')";
        }
        $waitNum = $this->oracleDb->query($sql);
        $data['waitNum'] = $waitNum['0']['NUM'] ?: 0;
//        $data['waitNum'] = $this->oracleDb->table('QUEUE')->where(['service' => $serviceId,'FCD'=>['<',$queueInfo->queue_time]])->count('1') ?: 0;

        //判断是否过号
        $data['passNumber'] = 0;
        $sql = "select to_char(SSD,'yyyy-mm-dd hh24:mi:ss') as SSDFORMATE, to_char(LCD,'yyyy-mm-dd hh24:mi:ss') as LCDFORMATE " .
            " from QUEUE_HISTORY where id='" . $queueInfo->queue_sn . "' and rownum=1";
        $queueHisInfo = $this->oracleDb->query($sql);
        if ($queueHisInfo) {
            $handle_time = strtotime($queueHisInfo['0']['LCDFORMATE']) - strtotime($queueHisInfo['0']['SSDFORMATE']);
            if ($handle_time < 60 && $handle_time > 0) {
                $data['passNumber'] = 1;
            }
        }

        //获取正在受理的编号
        $sql = "select A.CODE  from QUEUE_HISTORY A,QUEUE_HISTORY B " .
            " where  A.ID=B.ID AND A.service=$serviceId AND A.SSD=B.LCD AND A.SSD between to_date('" . date('Y-m-d ') . "00:00:00','yyyy-mm-dd hh24:mi:ss') " .
            " and to_date('" . date('Y-m-d ') . "23:59:59','yyyy-mm-dd hh24:mi:ss') order by A.SSD DESC";
        $queueHisInfo = $this->oracleDb->query($sql);
        $data['queueingCode'] = '暂未受理';
        if ($queueHisInfo) {
            $data['queueingCode'] = $queueHisInfo['0']['CODE'];
        }

        return ajax_return($data);

    }

    /**
     * 预约排队选择时间页面
     */
    public function orderQueueInfo()
    {
        $orderTime = input('ordertime', 0);  //预约时间  Y-m-d
        $branchId = input('branchid', 0);  //网点id
        if (empty($branchId)) {
            return ajax_return_error('参数为空');
        }
        if (empty($orderTime)) {
            $orderTime = $this->findOrderDay($branchId, '', 1);
        }
        if ($this->findOrderDay($branchId, $orderTime, 0) === false) {
            return ajax_return_error($this->result['msg'] . $orderTime);
        }
        //查询出当前时间的可预约时间
        $orderTimestamp = strtotime($orderTime);
        $formatDate = date('Y-m-d ', $orderTimestamp);

        $data = array('next' => '', 'prev' => '', 'date' => $orderTime);
        $data['next'] = $this->findOrderDay($branchId, $orderTime, 1);
        $data['prev'] = input('ordertime', 0) == '' ? '' : $this->findOrderDay($branchId, $orderTime, -1);
        $queueTime = Config::get('queue_time');
//        [['start' => '9:00', 'end' => '11:00'], ['start' => '14:00', 'end' => '18:00']]
        $timeLists = array();
        if ($queueTime) {
            foreach ($queueTime as $key => $dayTime) {
                $orderTime = strtotime($formatDate . $dayTime['start']);
                $endTime = strtotime($formatDate . $dayTime['end']);
                do {

                    $queueOrderNum = model('QueueOrder')->where(['branchid' => $branchId,
                        'status' => 1, 'queue_time' => $orderTime])->count(1) ?: 0;
                    if ($queueOrderNum < 1) {   //半小时只允许预约一个人，可选择的时间粒度为半小时
                        $timeLists[] = date('H:i', $orderTime);
                    }
                    $orderTime = strtotime('+30 minute', $orderTime);

                } while ($endTime > $orderTime);

            }
        }
        $data['timelist'] = $timeLists;


        return ajax_return($data);


    }

    /**
     * 提交预约信息，排号
     */
    public function submitOrderQueue()
    {
        $bisId = input('bisid', 0);  //业务id
        $branchId = input('branchid', 0);  //网点id
        $mobile = input('mobile', 0);  //手机号
        $trueName = input('truename', 0);  //真实姓名
        $orderTime = input('ordertime', 0);  //预约时间
        if (empty($bisId) || empty($branchId) || empty($mobile) || empty($trueName) || empty($orderTime)) {
            return ajax_return_error('参数为空');
        }

        $bisName = model('BusinessList')->where(['id' => $bisId, 'isdelete' => 0, 'status' => 1])->value('name') ?: '';
        $branchName = model('BranchList')->where(['id' => $branchId, 'isdelete' => 0, 'status' => 1])->value('name') ?: '';
        if (empty($bisName) || empty($branchName)) {
            return ajax_return_error('网点或业务未开放');
        }

        //TODO：判断预约时间是否可以预约
        $orderTimestamp = strtotime($orderTime);
        if (!$this->checkOrderQueueTimeNew($branchId, $bisId, $orderTimestamp)) {
            return ajax_return_error($this->result['msg']);
        }


        $orderResult = model('QueueOrder')->insert([
            'branchid' => $branchId,
            'branchname' => $branchName,
            'bisid' => $bisId,
            'bisname' => $bisName,
            'uid' => $this->uid,
            'truename' => $trueName,
            'mobile' => $mobile,
            'status' => 1,
            'queue_time' => $orderTimestamp,
            'create_time' => NOW_TIME
        ]);
        if ($orderResult) {


            $wechatAuth = new \WechatAuth(Config::get('weixin.appId'), Config::get('weixin.appSecret'));
            $wechatAuth->getAccessToken();

            $openid = model('Member')->where(['uid' => $this->uid])->value('openid');
            $data = array(
                'first' => array('value' => "您好,您已成功预约", 'color' => "#00CD00"),
                'keyword1' => array('value' => $bisName, 'color' => '#EE5C42'),
                'keyword2' => array('value' => $orderTime, 'color' => '#030303'),
                'remark' => array('value' => '系统将在' . $orderTime . '开始自动排队，请提前安排时间前往办理！', 'color' => '#030303'),
            );
            $result = $wechatAuth->doSendTpl($openid, '9eKcJnFTJ3eVA8rvgKSybYn_MBF0Qj9Q0bL7mZ1TLIY', 'http://bhgt.jslcwy.com/#/orderDone', $data);
            file_put_contents('./1.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($result) . PHP_EOL, FILE_APPEND);

            return ajax_return('success');
        } else {
            return ajax_return_error('error');
        }

    }

    /**
     * 提交信息，排号
     */
    public function submitQueue()
    {
        $bisId = input('bisid', 0);  //业务id
        $branchId = input('branchid', 0);  //网点id
        $mobile = input('mobile', 0);  //手机号
        $trueName = input('truename', 0);  //真实姓名
        if (empty($bisId) || empty($branchId) || empty($mobile) || empty($trueName)) {
            return ajax_return_error('参数为空');
        }


        if (!$this->checkOrderQueueTimeNew($branchId, $bisId, NOW_TIME)) {
            return ajax_return_error($this->result['msg']);
        }

        $this->getOracleDb($branchId);
        if ($this->result['error']) {
            return ajax_return_error($this->result['msg']);
        }

        //1.获取此业务的编码
        $bisCode = model('BusinessList')->where('id', $bisId)->value('code') ?: '';

        //2.获取排队机上的业务id
        $serviceId = $this->getRemoteServiceId($branchId, trim($bisCode));
        if($this->result['error']){
            $this->ajaxReturn($this->result);
        }
        $nextQueueCode = $this->oracleDb->table('QUEUE')->where(['service'=>$serviceId, 'CODE'=>['like','A%']])
            ->order('CODE', 'DESC')->value('CODE');

//        $sql = "select CODE from QUEUE " .
//            " where SERVICE=$serviceId AND CODE like 'Y%'  order by FCD desc";
//        $remoteQueueCode = $this->oracleDb->query($sql);

        if (empty($nextQueueCode)) {

            $sql = "select CODE  from QUEUE_HISTORY " .
                " where service=$serviceId AND CODE like 'A%'   AND FCD between to_date('" . date('Y-m-d ') . "00:00:00','yyyy-mm-dd hh24:mi:ss') " .
                " and to_date('" . date('Y-m-d ') . "23:59:59','yyyy-mm-dd hh24:mi:ss') order by FCD DESC";
            $queueHisCode = $this->oracleDb->query($sql);
//            $nextQueueCode = $bisCode . '001';
            $nextQueueCode = 'A001';
            if ($queueHisCode) {
                $nextQueueCode = ++$queueHisCode['0']['CODE'];
            }
        } else {
            $nextQueueCode = ++$nextQueueCode;
        }

        $i = 0;
        do {
            $remoteQueueId = get_uuid(32);
            $remoteQueueExits = $this->oracleDb->table('QUEUE')->find($remoteQueueId);
            $i++;
            if ($i > 5) {
                return ajax_return_error('队列id生成失败');
            }
        } while ($remoteQueueExits);
        $insertOracleQueueSql = "insert into QUEUE(ID,CODE,SERVICE,NETWORK,FCD) values('$remoteQueueId','$nextQueueCode',$serviceId,0,to_date('" . date('Y-m-d H:i:s') . "','yyyy-mm-dd hh24:mi:ss'))";
        $boolean = $this->oracleDb->execute($insertOracleQueueSql);


        if ($boolean) {

            model('Queue')->insert([
                'queue_sn' => $remoteQueueId,
                'queue_code' => $nextQueueCode,
                'branchid' => $branchId,
                'serviceid' => $serviceId,
                'bisid' => $bisId,
                'type' => 2,  //在线排队
                'uid' => $this->uid,
                'truename' => $trueName,
                'mobile' => $mobile,
                'queue_time' => NOW_TIME,
                'create_time' => NOW_TIME
            ]);
            $openid = model('Member')->where(['uid' => $this->uid])->value('openid');

            //排队人数
            $waitNum = $this->oracleDb->table('QUEUE')->where(['service' => $serviceId])->count('1') ?: 0;

            //获取正在受理的编号
            $sql = "select A.CODE  from QUEUE_HISTORY A,QUEUE_HISTORY B " .
                " where  A.ID=B.ID AND A.service=$serviceId AND A.SSD=B.LCD AND A.SSD between to_date('" . date('Y-m-d ') . "00:00:00','yyyy-mm-dd hh24:mi:ss') " .
                " and to_date('" . date('Y-m-d ') . "23:59:59','yyyy-mm-dd hh24:mi:ss') order by A.SSD DESC";
            $queueHisInfo = $this->oracleDb->query($sql);
            $queueingCode = '未叫号';
            if ($queueHisInfo) {
                $queueingCode = $queueHisInfo['0']['CODE'];
            }


            $wechatAuth = new \WechatAuth(Config::get('weixin.appId'), Config::get('weixin.appSecret'));
            $wechatAuth->getAccessToken();

            $data = array(
                'first' => array('value' => "您好,您已成功排队", 'color' => "#00CD00"),
                'keyword1' => array('value' => $queueingCode, 'color' => '#EE5C42'),
                'keyword2' => array('value' => $nextQueueCode, 'color' => '#030303'),
                'keyword3' => array('value' => $waitNum, 'color' => '#EE9A00'),
                'remark' => array('value' => $waitNum <= 1 ? '请马上到窗口办理！' : '请耐心等待！', 'color' => '#030303'),
            );

            $result = $wechatAuth->doSendTpl($openid, 'cUnWLTczU0kO2TffA7RIQktB_uYpPutZMcQOB9seF2Q', 'http://bhgt.jslcwy.com/#/registerDone', $data);
            file_put_contents('./2.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($result) . PHP_EOL, FILE_APPEND);
            return ajax_return('success');
        } else {
            return ajax_return_error('error');
        }

    }

    public function articleInfo()
    {
        $id = input('id', 0);
        if (empty($id)) {
            return ajax_return_error('参数为空');
        }
        $model = model('ArticleList');
        $info = $model->where('isdelete', 0)->find($id);
        if ($info) {
            $info->content = htmlspecialchars_decode($info->content);
        } else {
            $info = new \stdClass();
        }
        return ajax_return($info);
    }

    /**
     * 各网点办理详情
     */
    public function branchsInfo()
    {
//        $myLng = input('mylng', '');  //用户地理位置经度
//        $myLat = input('mylat', '');  //用户地理位置纬度
//        $orderType = input('ordertype', 0);  //0 按距离排序  1：按排队人数
//        if ($orderType == 0 && (empty($myLng) || empty($myLng))) {
//            return ajax_return_error('参数有误');
//        }
        $model = model('BranchList');
        $lists = $model->field('id,name,status')->where(['isdelete' => 0])->select();
        if ($lists) {
            $formatDate = date('Y-m-d ');
            $startTime = strtotime($formatDate);
            foreach ($lists as &$list) {
                $list->queueNum = model('Queue')->where(['branchid' => $list->id])->count('1') ?: 0;
                $list->queueHisNum = model('QueueHistory')->where(['branchid' => $list->id,'queue_time'=>['>', $startTime]])->count('1') ?: 0;
                $list->queueingCode = model('QueueHistory')->where(['branchid' => $list->id, 'queue_status'=>2, 'queue_time'=>['>', $startTime]])->order('queue_time','desc')->value('queue_code')?:'无人办理';
            }
        }
//        if ($orderType == 0) {
//            $lists = obj_list_sort_by($lists, 'distance', 'asc');
//        } else {
//            $lists = obj_list_sort_by($lists, 'queueNum', 'asc');
//        }
        return ajax_return($lists);

    }

}
